#!/bin/bash
set -e

# 进入仓库根目录
cd /linux-0-0-1/os-elephant/zlx_project/linux_0.12

# 初始化 git
git remote set-url origin https://1844066342%40qq.com:shixi123aA@gitee.com/ZLX0326/linux_0.12.git

# 进入工作目录
cd pj02

# 文件列表
files=(
    "./img/hd60M.img"
    "./bochsrc"
)

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

for file in "${files[@]}"; do
    if [ -f "$file" ]; then
        echo -e "${GREEN}✔ 文件存在: $file${NC}"
    else
        echo -e "${RED}❌ 文件不存在: $file${NC}"
    fi
done

# 清空磁盘锁定文件
if [ $(find ./ -type f -name "*.lock" | wc -l) -eq 0 ]; then
    echo -e "${GREEN}✔ 磁盘未被锁定${NC}"
else
    echo -e "${RED}❌ 磁盘锁定正在清理...${NC}"
    find ./ -type f -name "*.lock" -exec rm -f {} +
fi

# 1. 清空磁盘前512字节
dd if=/dev/zero of=./img/hd60M.img bs=512 count=1 conv=notrunc > /dev/null 2>&1
echo -e "${GREEN}✔ 磁盘MRB清空${NC}"

# 2. 编译mbr，并写入磁盘
nasm -o ./code/mbr.bin ./code/mbr.S -l ./code/mbr.lst
echo -e "${GREEN}✔ 编译完毕${NC}"
dd if=./code/mbr.bin of=./img/hd60M.img bs=512 count=1 conv=notrunc > /dev/null 2>&1
echo -e "${GREEN}✔ 磁盘MRB写入${NC}"

# 3. 检查mbr.bin是否存在
if [ -f ./code/mbr.bin ]; then
    echo -e "${GREEN}✔ ./code/mbr.bin 存在${NC}"
else
    echo -e "${RED}❌ ./code/mbr.bin 不存在${NC}"
    exit 1
fi

# 4. 检查磁盘前512字节最后两字节是否为55AA
last2=$(xxd -p -l 2 -s 510 ./img/hd60M.img)
if [[ "$last2" == "55aa" || "$last2" == "55AA" ]]; then
    echo -e "${GREEN}✔ 镜像前512字节结尾为55AA${NC}"
else
    echo -e "${RED}❌ 镜像前512字节结尾不是55AA，而是: $last2${NC}"
fi

sleep 1

# 进入根目录
cd /linux-0-0-1/os-elephant/zlx_project/linux_0.12/
random_num=$(printf "%08d" $(( ( RANDOM * RANDOM ) % 100000000 )))

# 推送 git
echo -e "${GREEN}✔ 正在推送到git ... ${NC}"
git add .
git commit --allow-empty -m "推送 - $random_num"
git push
echo -e "${GREEN}✔ 推送完毕 ... ${NC}"